<?php

namespace app\admin\model;

use app\common\model\BaseModel;

/**
 * 后台用户模型
 * Class AdminUser
 * @package app\admin\model
 */
class AdminUser extends BaseModel
{
    protected $name = 'admin_user';

    protected $pk = 'admin_user_id';
    /**
     * 追加字段
     * @var array
     */
    protected $append = [
        'AdminMenu',
        'LoginCity'
    ];
    
    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [
        'password',
        'update_time'
    ];

    public function getLastLoginTimeAttr($value,$data){
        return date('Y-m-d H:i:s',$value);
    }

    public function getbeforeLoginTimeAttr($value,$data){
        return date('Y-m-d H:i:s',$value);
    }

    public function getLoginCityAttr($value,$data){
        $ip = $data['last_login_ip'] != '127.0.0.1'?$data['last_login_ip'] :'219.131.10.221';
        return getCity($ip);
    }
    

    /**
     * 关联用户角色表
     * @return \think\model\relation\BelongsTo
     */
    public function AdminRole()
    {
        $module = self::getCalledModule() ?: 'common';
        return $this->BelongsTo("app\\{$module}\\model\\AdminRole");
    }

    /**
     * 关联头像
     * @return \think\model\relation\HasOne
     */
    public function image()
    {
        return $this->hasOne('uploadFile', 'file_id', 'image_id');
    }

    
    // 登录
    public function login($param){
        extract($param);

        // 合理性校验
        // if( !isset($key) || empty($key) || !isset($VerifyCode) || empty($VerifyCode))
        // {
        //     $this->error = '验证码不能为空!';
        //     return false;
        // }

        // // 检查验证码
        // if(checkVerify($VerifyCode,$key) === false)
        // {
        //     $this->error = '验证码错误!';
        //     return false;
        // }
        // 验证用户名密码是否正确
        if (!$user = self::with(['AdminRole'])->where([
            'username'=>$username,
            'password'=>$password
        ])->find()) {
            $this->error = '登录失败, 用户名或密码错误!';
            return false;
        }
        $user->save(['last_login_ip'=>$user['before_login_ip'],'before_login_ip'=>request()->ip(),'last_login_time'=>strtotime($user['before_login_time']),'before_login_time'=>time()]);
        return $user;
    }

    // 用户详细
    public function detail($admin_user_id){
        return $this->find($admin_user_id);
    }

    // 获取用户初始化数据
    public function initUser($admin_user_id){
        // 获取用户基础数据
        $result =  $this->with(['AdminRole','image'])->find($admin_user_id);
        // 获取用户权限菜单
        $result['AdminMenu'] = (new AdminMenu)->getRoleAuthorityMenu($result['AdminRole']);
        // 前端用不上,删除了
        // $result['authority_menu_url'] = Cache::get('admin_authority_menu_url_' . $result['AdminRole']['admin_role_id']);
        return $result;
    }

    // 管理员列表
    public function getAll(){
        return $this->with(['AdminRole'])->select();
    }

     // 新增管理员
     public function add($param){
        if(empty($param['username']))
        {
            $this->error = "必须填写管理员用户名";
            return false;
        }
        if(empty($param['admin_role_id']))
        {
            $this->error = "必须选择用户角色";
            return false;
        }
        if(empty($param['password']))
        {
            $this->error = "必须填写密码";
            return false;
        }
        $param['password'] = md5($param['password']);
        if($this->where(['username'=>$param['username']])->value('admin_user_id'))
        {
            $this->error = "该用户名已存在";
            return false;
        }
        try {
            $this->startTrans();
            // 新增
            $this->save($param);
            $this->commit();
            return true;
        } catch (\Throwable $th) {
            $this->rollback();
            //throw $th;
            $this->error = $th->getMessage();
            return false;
        }
    }

    // 编辑管理员
    public function edit($param){
        if(empty($param['admin_role_id']))
        {
            $this->error = "必须选择用户角色";
            return false;
        }
        if(empty($param['username']))
        {
            $this->error = "必须填写管理员名称";
            return false;
        }
        // 密码为空不更新(前端机(傻)智(逼)的的认为密码会被拦截,所以由他那边自行MD5传过来,后端就不做MD5加密了)
        if(isset($param['password']) && empty($param['password']))
        {
            unset($param['password']);
        }
        if($this->where('username = "'.$param['username'] .'" AND admin_user_id <> '.$param['admin_user_id'])->value('admin_user_id') )
        {
            $this->error = "该用户名已存在";
            return false;
        }
        if(empty($param['nickname']))
        {
            $this->error = "该必须填写昵称";
            return false;
        }
        try {
            // 更新
            $this->exists(true)->save($param);

            return true;
        } catch (\Throwable $th) {
            //throw $th;
            $this->error = $th->getMessage();
            return false;
        }
    }

    public function remove($admin_user_id){
        // 判断是否超管
        if($admin_user_id == 1)
        {
            $this->error = '无法删除超级管理员!';
            return false;
        }
        try {
            $this->startTrans();
            // 删除管理员
            if($this->where(['admin_user_id'=>$admin_user_id])->delete())
            {
                $this->commit();
                return true;
            }
            $this->rollback();
            return false;
        } catch (\Throwable $th) {
            //throw $th;
            $this->error = $th->getMessage();
            $this->rollback();
            return false;
        }
    }
}